package kg.aibek.dc;

public class AdaptiveModel {
	public static final int BIT_LENGTH = 16;
	static final int SIZE = 256;
	int[] table = new int[SIZE]; // Array which's index are char and values are
									// frequencies
	int totalFrequency = 0;
	int maxCumulativeFrequency = 16383; // Maximum cumulative frequency. When
										// the total frequency will exceed this
										// value the frequencies will be halved
	int[] cumulativeFrequency = new int[SIZE];

	public AdaptiveModel() {
		for (int i = 0; i < table.length; i++) {
			table[i] = 1;
			totalFrequency += table[i];
			cumulativeFrequency[i] = totalFrequency;
		}
	}

	public void addContext(char ch) {
		table[ch]++;
		totalFrequency++;

		for (int i = ch; i < table.length; i++) {
			cumulativeFrequency[i]++;
		}

		if (totalFrequency > maxCumulativeFrequency) {
			totalFrequency = 0;
			for (int i = 0; i < table.length; i++) {
				table[i] = (table[i] + 1) / 2;
				totalFrequency += table[i];
				cumulativeFrequency[i] = totalFrequency;
			}
		}
	}

	public int getTotalFrequency() {
		return totalFrequency;
	}

	public void setTotalFrequency(int totalFrequency) {
		this.totalFrequency = totalFrequency;
	}

	public int[] getCumulativeFrequency() {
		return cumulativeFrequency;
	}

	public void setCumulativeFrequency(int[] cumulativeFrequency) {
		this.cumulativeFrequency = cumulativeFrequency;
	}

}
